package com.gmail.blackdog1987.carcare.db.dao;

import android.content.ContentValues;
import android.database.Cursor;

import com.gmail.blackdog1987.carcare.App;
import com.gmail.blackdog1987.carcare.db.DbHelper;
import com.gmail.blackdog1987.carcare.entity.TUser;


public class UserDao {

	private DbHelper mDb = App.getDbHelper();
	
	private ContentValues entityToContentValues(TUser user) {
		ContentValues cv = new ContentValues();
		cv.put(TUser.Field.pwd.toString(), user.pwd);
		cv.put(TUser.Field.id.toString(), user.id);
		cv.put(TUser.Field.username.toString(), user.username);
		return cv;
	}
	
	/**
	 * 先清空用户信息后保存新的用户信息
	 * 
	 * @param user
	 * @return
	 */
	public boolean saveUser(TUser user) {
		mDb.delete(TUser.TABLE, " 1=1;");
		mDb.insert(TUser.TABLE, entityToContentValues(user));
		return false;
	}
	
	/**
	 * 获取用户信息
	 * 
	 * @return 用户信息
	 */
	public TUser getUser() {
		Cursor cursor = null;
		TUser user = null;
		try {
			cursor = mDb.query(TUser.TABLE, null, null);
			if (cursor == null || cursor.getCount() == 0) {
				return null;
			}
			cursor.moveToFirst();
			user = new TUser();
			user.id = cursor.getInt(cursor.getColumnIndex(TUser.Field.id.toString()));
			user.username = cursor.getString(cursor.getColumnIndex(TUser.Field.username.toString()));
			user.pwd = cursor.getString(cursor.getColumnIndex(TUser.Field.pwd.toString()));
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
				cursor = null;
			}
		}
		return user;
	}


	public void clear() {
		String[] delSql = new String[] { "DELETE from " + TUser.TABLE };
		mDb.execSQLTransaction(delSql);
	}
}
